/**
 * Created by kevin on 2017/6/26.
 */
let env = require("./env");
let filePath = env.isDevelop() ? "../config/develop.json" : "../config/production.json";

var URL = require('url');
var web = require(filePath);
var fs = require('fs');
var website = function () {

};

website.webname = function () {
    return web.name;
};

website.ipack = function () {
    return web.ipack;
};

website.url = function (req) {
    let host = req.protocol + '://' + req.headers.host;
    return  host;
};

website.email = function () {
    return web.email;
};

website.logo = function () {
    return web.logo;
};

website.update = function (info,cb) {
    if (!info) {
        if (cb) {
            cb(null);
        }
        return;
    }
    let ninfo = {
        name : info.name || web.name,
        email : info.email || web.email,
        ipack : web.ipack,
        logo : info.logo || web.logo
    };
    fs.readFile(filePath,'utf8',function (err,data) {
        if (err) {
            throw err.message;
        }
        let db = JSON.parse(data).db;
        ninfo["db"] = db;

        data = web.db;
        fs.writeFile(data,(err) => {
            // if (err) throw err;
            delete require.cache[require.resolve(filePath)];
            if (cb) {
                cb(err);
            }
        });
    });

    fs.writeFile(filePath,JSON.stringify(ninfo),(err) => {
        // if (err) throw err;
        delete require.cache[require.resolve('../config/website.conf.json')];
        if (cb) {
            cb(err);
        }
    });
};
module.exports = website;
